package com.tucc.hello.leetcode.no1_400.no1_200.no41_60.no56;

import java.util.*;
import java.util.stream.Stream;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] result = solution.merge(intervals);
        solution.printArr(result);
    }

    public int[][] merge(int[][] intervals) {
        int[][] result = null;
        Arrays.sort(intervals, (a, b) -> {
            if (a[0] == b[0]) {
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            int[] cur = intervals[i];
            boolean merged = false;
            for (int j = 0; j < list.size(); j++) {
                int[] temp = list.get(j);
                if (temp[0] <= cur[0] && temp[1] >= cur[1]) {
                    // 完全包含的情况
                    merged = true;
                } else if (temp[1] < cur[1] && temp[1] >= cur[0]) {
                    // 1,3  2,4
                    temp[1] = cur[1];
                    merged = true;
                }
            }
            if (!merged) {
                list.add(cur);
            }
        }
        result = new int[list.size()][];
        Iterator<int[]> iterator = list.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            result[i++] = iterator.next();
        }
        return result;
    }

    private void printArr(int[][] result) {
        if (result != null) {
            for (int i = 0; i < result.length; i++) {
                System.out.println(result[i][0] + " " + result[i][1]);
            }
        }
    }


}
